var express = require('express');
var router = express.Router();
var mysql = require('mysql');
const { mysqlCreate } = require('./utils');

//连接数据库
let conn = mysqlCreate();

//用户注册
router.post('/', (req, res) =>{
  conn = mysql.createConnection(conn.config);
  //连接数据库
  conn.connect();
  const {username, password} = req.body;
  // 插入sql语句
  var regssql = `insert into user(name,password) values('${username}','${password}')`;
  // 查询sql语句
  var selsql = `select name from user where name='${username}'`;

  //把用户注册信息注册到数据库中
  function regfun(){
    conn.query(regssql, (err, result)=>{
      if(err){
        res.json({code: -1, message:"插入失败"})
      }else{
        res.json({code: 10000, message:"插入成功"})
      }
    })
  };
  //检查用户注册的数据库中是否存在
  conn.query(selsql, (err,result)=>{
    if(err){
      console.log(err)
      return
    }
    if(result == ""){
      regfun()
    }else{
      res.json({code: -1, message: "用户名被注册了，请重新输入"})
    }
    conn.end();
  })
})

module.exports = router;